<?php
//error_reporting(1);

set_time_limit(0);
global $wpdb;

function savePost($postInfo){
	global $wpdb;

	//////// adding post data
	$my_post = array(
		 'post_title' => trim($postInfo->companyName),
		 'post_content' => trim($postInfo->companyDetail),
		 'post_status' => 'publish',
		 'post_author' => 1,
		 'post_category' => array(12, 109)
	  );
	 $pID=wp_insert_post( $my_post );	
	
	
	  
	///////// adding meta Information
	add_post_meta($pID, 'emailAddress', trim($postInfo->contactEmail));
	add_post_meta($pID, 'phoneNumber', trim($postInfo->companyPhone));
	add_post_meta($pID, 'contactPerson', trim($postInfo->contactPerson));
	add_post_meta($pID, 'siteURL', trim($postInfo->companyURL));
	add_post_meta($pID, 'youTubeVideo', '');
	add_post_meta($pID, 'address', trim($postInfo->companyAddress));


	//////// check for logo file
	if($postInfo->logoFile!=""){
		$pInf=wp_upload_dir();
		$basePath=$pInf['basedir']."/companiesLogo/";
		$filePath=$basePath.$postInfo->logoFile;
		if(file_exists($filePath)){
			//echo "<br>File Found ".$postInfo->logoFile;
			$ext = end(explode(".", $postInfo->logoFile));
			$ext=strtolower($ext);
			if($ext=="gif" || $ext=="jpg" || $ext=="png"){
				add_post_meta($pID, 'logoName', $postInfo->logoFile);
				add_post_meta($pID, 'logoSource', 'fixed');
			}
			
		//	$fileInfo = getimagesize($filePath);
		//	if(!empty($fileInfo)){
		//		$mime = $fileInfo['mime'];
		//		echo $mime;
		//	}
		}
	}

	$wpdb->query("update companies set import2Done=1 Where companyID=".$postInfo->companyID);
}

$myrows = $wpdb->get_results( "SELECT * FROM companies Where importDone=1 AND import2Done=0 Limit 100");

//print "<pre>";
//print_r($myrows);
//print "</pre>";

foreach($myrows as $row){
	savePost($row);
}

$myrows =(array) $wpdb->get_results( "SELECT * FROM companies Where import2Done=0");
if(count($myrows)==0) echo "<br>All Done"; else echo "<br>There Are ".count($myrows)." Records Waiting for Processing. Please Refresh It Again.";